import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputValue: '',
    nextId: 5,
    key: 'all'
  },
  mutations: {
    initList(state, list) {
      state.list = list
    },
    setInputValue(state, val) {
      state.inputValue = val
    },
    setChecked(state, id) {
      state.list[id].done = !state.list[id].done
    },
    addList(state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
    },
    removeList(state, id) {
      const index = state.list.findIndex(item => item.id === id)
      if (index !== -1) {
        state.list.splice(index, 1)
      }
    },
    clear(state) {
      this.state.list = this.state.list.filter(item => item.done === false)
    },
    changeKey(state, key) {
      this.state.key = key
    }
  },
  actions: {
    getList(context) {
      axios.get('/list.json').then(({ data }) => {
        context.commit('initList', data)
      })
    }
  },
  getters: {
    undone(state) {
      return state.list.filter(item => item.done === false).length
    },
    infoList(state) {
      switch (state.key) {
        case 'undone': return state.list.filter(item => item.done === false)
        case 'done': return state.list.filter(item => item.done === true)
        default: return state.list
      }
    }
  }
})
